 #!/usr/bin/python
 # -*- coding: utf-8 -*-


# Echo server program
import socket
import os

HOST = ''                 # Symbolic name meaning the local host
PORT = 8760              # Arbitrary non-privileged port

HOST = ''
PORTNO = 60007 # port between firewallagent and bbw2

#orderno, sourceipfrom, sourceipto, destinationipfrom, destinationipto, sourceportfrom, sourceportto, destinationportfrom, destinationportto=None,None,None,None,None,None,None,None,None

data = None
orderno = None
ordr = None

while 1:
		
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s.bind((HOST, PORT))
	s.listen(1)
	conn, addr = s.accept()
	print 'Connected by', addr
	while 1:
		data = conn.recv(1024)
		if not data: break
		#conn.send(data) # i got the message here now should send it to the bbw2
		conn.send("OK")
		
		if not orderno:
		
			try:
				ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				ss.connect((HOST, PORTNO))
				
				ss.send(data)
				datartr=None
				
				while not datartr: 
					datartr=ss.recv(1024) # wait till bbw2 sends something
				
				orderno=datartr # got the orderno
				ss.close()
				
			except:
				continue
						
			
		li=data.split(',')
		print "orderno", orderno, "protokol", li[0], "source", li[1], "source port", li[2], "destination", li[3], "destination port", li[4], "action", li[5], "adding"
		
		# add the protokol part
		if li[0].lower() != "all": p=li[0].lower()
		else: p="all"
		protokol="-p %s" % p
	    
		#check whether there is a range description in source ip
		sourceipfrom=""
		sourceipto=""
		if li[1].find(":") != -1:
			sourceip=li[1].strip().split(":")
			sourceipfrom=sourceip[0]
			#print sourceipfrom
			sourceipto=sourceip[1]
			#print sourceipfrom
	
		else:
		    	sourceipfrom=li[1].strip()
		    
	
	   	# check whether there is a range description in destination ip
	     	destinationipfrom=""
	     	destinationipto=""
	     	if li[3].find(":") != -1:
		    	destinationip=li[3].strip().split(":")
		    	destinationipfrom=destinationip[0]
		    	destinationipto=destinationip[1]
	     	else:
		     	destinationipfrom=li[3].strip()
		     

		# check whether the source port is defined as range
		sourceportfrom=""
		sourceportto=""
		if li[2].find(":") != -1:
			sourceport=li[2].strip().split(":")
			sourceportfrom=sourceport[0]
			sourceportto=sourceport[1]
		elif li[2] == "*":
			sourceportfrom="0"
			sourceportto="65535"
		else: sourceportfrom = li[2]
			
		# check whether the source port is defined as range
		destinationportfrom=""
		destinationportto=""
		#print li[3]
		if li[4].find(":") != -1:
			#print "here2"
			destinationport=li[4].strip().split(":")
			destinationportfrom=destinationport[0]
			destinationportto=destinationport[1]
			print destinationportfrom, destinationportto
		elif li[4] == "*":
			destinationportfrom="0"
			destinationportto="65535"
		else: destinationportfrom = li[4]
				
		srcipto=""
		if sourceipto != "": srcipto = "-"+sourceipto # sourceipfrom+srcipto
		dstipto=""
		if destinationipto != "": dstipto = "-"+destinationipto # destinationipfrom+dstipto
		    
		if sourceportto=="": srcport=sourceportfrom
		else: srcport = sourceportfrom + ":" + sourceportto # use srcport variable in iptables
		    
		if destinationportto=="": dstport=destinationportfrom
		else: dstport = destinationportfrom + ":" + destinationportto # use srcport variable in iptables	
		
		#print li[4].strip().lower() == "accept"
		
		#print type(orderno)
		
		if srcipto != "": 
			srcrangetxt = "--src-range"
			srctxt = ""
		else: 
			srcrangetxt = ""
			srctxt = "-s"
			 
		if dstipto != "": 
			dstrangetxt = "--dst-range"
			dsttxt = ""
		else: 
			dstrangetxt = ""
			dsttxt = "-d"
			
		if srcipto != "" or dstipto != "": matchtxt = "-m iprange"
		else: matchtxt=""
		
		if li[5].strip().lower() == "accept":
			#print orderno
			
			print ("/sbin/iptables -I FORWARD %s %s --sport %s --dport %s %s %s %s %s %s %s %s -j ACCEPT" % (orderno.strip(), protokol, srcport, dstport, matchtxt, srcrangetxt, srctxt, sourceipfrom+srcipto,dstrangetxt, dsttxt, destinationipfrom+dstipto))
			
		    	os.popen("/sbin/iptables -I FORWARD %s %s --sport %s --dport %s %s %s %s %s %s %s %s -j ACCEPT" % (orderno.strip(), protokol, srcport, dstport, matchtxt, srcrangetxt, srctxt, sourceipfrom+srcipto, dstrangetxt, dsttxt, destinationipfrom+dstipto))
		     
	    	if li[5].strip().lower() == "reject":
			
			print ("/sbin/iptables -I FORWARD %s %s --sport %s --dport %s %s %s %s %s %s %s %s -j REJECT --reject-with tcp-reset" % (orderno.strip(), protokol, srcport, dstport, matchtxt, srcrangetxt, srctxt, sourceipfrom+srcipto, dstrangetxt, dsttxt, destinationipfrom+dstipto))
			
		    	os.popen("/sbin/iptables -I FORWARD %s %s --sport %s --dport %s %s %s %s %s %s %s %s -j REJECT --reject-with tcp-reset" % (orderno.strip(), protokol, srcport, dstport, matchtxt, srcrangetxt, srctxt, sourceipfrom+srcipto, dstrangetxt, dsttxt, destinationipfrom+dstipto))
			
	    	if li[5].strip().lower() == "drop":
			print ("/sbin/iptables -I FORWARD %s %s --sport %s --dport %s %s %s %s %s %s %s %s -j REJECT --reject-with tcp-reset" % (orderno.strip(), protokol, srcport, dstport, matchtxt, srcrangetxt, srctxt, sourceipfrom+srcipto, dstrangetxt, dsttxt, destinationipfrom+dstipto))
			
		    	os.popen("/sbin/iptables -I FORWARD %s %s --sport %s --dport %s %s %s %s %s %s %s %s -j REJECT --reject-with tcp-reset" % (orderno.strip(), protokol, srcport, dstport, matchtxt, srcrangetxt, srctxt, sourceipfrom+srcipto, dstrangetxt, dsttxt, destinationipfrom+dstipto))
		
		print "done"
	    	print "..."
		ordr = orderno
		data, orderno = None, None
		break
	
	conn.close()
	s.close()
	# send the port number to the server agent
	#print ordr
	sss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sss.connect((HOST, PORT))
	sss.send(ordr)
	data=sss.recv(1024)
	sss.close()
